﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UCodeFirstMacroPage.cs" company="CodePlex">
//   The MIT License
//   Copyright (c) 2013 Julien Blin
//   
//   Permission is hereby granted, free of charge, to any person obtaining a copy
//   of this software and associated documentation files (the "Software"), to deal
//   in the Software without restriction, including without limitation the rights
//   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is
//   furnished to do so, subject to the following conditions:
//   
//   The above copyright notice and this permission notice shall be included in
//   all copies or substantial portions of the Software.
//   
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//   THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace UCodeFirst.Macros
{
    using System;
    using System.Linq;

    using UCodeFirst.Converters;

    using Umbraco.Core;
    using Umbraco.Web.Macros;

    /// <summary>
    /// Base class for uCodeFirst macro views.
    /// </summary>
    /// <typeparam name="T">
    /// The <see cref="MacroParametersBase"/> that defines macro parameters.
    /// </typeparam>
    public abstract class UCodeFirstMacroPage<T> : PartialViewMacroPage
        where T : MacroParametersBase, new()
    {
        /// <summary>
        /// The macro parameters.
        /// </summary>
        private T strongParameters;

        /// <summary>
        /// Gets the macro parameters.
        /// </summary>
        public T StrongParameters
        {
            get
            {
                return this.strongParameters ?? (this.strongParameters = this.LoadParameters());
            }
        }

        /// <summary>
        /// Loads the macro parameters.
        /// </summary>
        /// <returns>
        /// The loaded parameters.
        /// </returns>
        protected virtual T LoadParameters()
        {
            var result = new T();
            var properties = typeof(T).GetProperties().Where(x => x.HasAttr<MacroPropertyAttribute>());
            foreach (var targetPropertyInfo in properties)
            {
                try
                {
                    var targetPropertyAttr = targetPropertyInfo.GetAttr<MacroPropertyAttribute>();
                    if (this.Model.MacroParameters.ContainsKey(targetPropertyInfo.Name))
                    {
                        var setMethod = targetPropertyInfo.GetSetMethod(true);
                        if (setMethod == null)
                        {
                            throw new UCodeFirstException(Resources.UnableToFindSetMethod.InvariantFormat(targetPropertyInfo.Name));
                        }

                        var converter = targetPropertyAttr.Converter == null
                                    ? StandardConverters.Converters.ContainsKey(targetPropertyInfo.PropertyType) ? StandardConverters.Converters[targetPropertyInfo.PropertyType] : null
                                    : targetPropertyAttr.Converter.CreateInstance<IConverter>();

                        if (converter == null)
                        {
                            throw new UCodeFirstException(Resources.UnableToFindConverter.InvariantFormat(targetPropertyInfo));
                        }

                        setMethod.Invoke(result, new[] { converter.Read(targetPropertyInfo, this.Model.MacroParameters[targetPropertyInfo.Name] as string) });   
                    }
                }
                catch (Exception ex)
                {
                    throw new UCodeFirstException(Resources.ErrorWhileBindingMacroParameterValue.InvariantFormat(this.Model.MacroParameters[targetPropertyInfo.Name], targetPropertyInfo), ex);
                }
            }

            return result;
        }
    }
}
